<template>
  <div class='big'>
    <!-- 返回按钮 -->
    <div class="back-button-container">
      <button class="back-button" @click="goBack">返回</button>
    </div>
    
    <div class='login'>
      <h1 class='title'>{{ title }}</h1>
      <div class='logins centered-content'>
        <div class="centered-container">
          <input 
            v-model="email"
            type="email"
            placeholder="邮箱账号"
            class="account-input"
            @blur="validateEmail"
          >
        </div>  
        <div class="verify-container">
          <input 
            v-model="verifyCode"
            type="text"
            placeholder="验证码"
            class="verify-input"
            @keyup.enter="verifyCodeFunc"
            maxlength="6"
          >
          <button 
            @click="sendVerifyCode"
            :disabled="isSending || countdown > 0 ||!email"
            class="send-code-btn"
          >
            {{ countdown > 0? `${countdown}秒后重新发送` : '获取验证码' }}
          </button>
        </div>
        <div class="centered-container">
          <input 
            v-model="password"
            type="password"
            placeholder="新密码（6位以上）"
            class="account-inputo"
            @keyup.enter="handlePasswordChange"
          >
        </div>
        <div class="centered-container">
          <input 
            v-model="passwordt"
            type="password"
            placeholder="确认密码"
            class="account-inputt"
            @keyup.enter="handlePasswordChange"
          >
        </div>
        <button 
          @click="handlePasswordChange"
          :disabled="loading || formInvalid"
          class='button'
        >
          {{ loading? '处理中...' : '修改密码' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const title = ref('爱韵动-找密码');
const email = ref('');
const verifyCode = ref('');
const password = ref('');
const passwordt = ref('');
const loading = ref(false);
const isSending = ref(false);
const countdown = ref(0);
const agreed = ref(true);
const isVerified = ref(false);
const router = useRouter();
let countdownTimer: NodeJS.Timeout | null = null;

const API_BASE_URL = 'http://localhost:3000';
const emailRegExp = /^[^@]+@qq\.com$/;

const goBack = () => {
  router.push('/login');
};

const formInvalid = computed(() => {
  const isValidEmail = email.value && emailRegExp.test(email.value);
  return!isValidEmail ||!verifyCode.value || 
         !password.value ||!passwordt.value || 
         password.value!== passwordt.value || 
         password.value.length < 6 ||
         !agreed.value ||!isVerified.value;
});

const handlePasswordChange = async () => {
  if (formInvalid.value) {
    showValidationMessage();
    return;
  }

  loading.value = true;
  
  try {
    // 确保请求参数准确，这里newPassword对应后端接收的参数名
    const response = await axios.post(`${API_BASE_URL}/update-password`, {
      email: email.value,
      verificationCode: verifyCode.value,
      newPassword: password.value
    });
    
    // 详细判断后端返回状态
    if (response.data.code === 200) {
      ElMessage.success('密码修改成功');
      router.push('/login');
    } else if (response.data.code === 400) {
      ElMessage.warning(response.data.msg || '请求参数有误');
    } else if (response.data.code === 500) {
      ElMessage.error(response.data.msg || '服务器内部错误');
    } else {
      ElMessage.error('未知错误，请联系管理员');
    }
  } catch (error: any) {
    console.error('请求错误:', error);
    if (error.response) {
      ElMessage.error(error.response.data.msg || '操作失败，请稍后重试');
    } else {
      ElMessage.error('网络连接错误，请检查网络');
    }
  } finally {
    loading.value = false;
  }
};

const showValidationMessage = () => {
  if (!email.value) {
    ElMessage.warning('请输入邮箱');
    return;
  }
  if (!emailRegExp.test(email.value)) {
    ElMessage.warning('请输入正确的QQ邮箱格式');
    return;
  }
  if (!verifyCode.value) {
    ElMessage.warning('请输入验证码');
    return;
  }
  if (!password.value) {
    ElMessage.warning('请输入新密码');
    return;
  }
  if (password.value.length < 6) {
    ElMessage.warning('密码必须至少6位');
    return;
  }
  if (!passwordt.value) {
    ElMessage.warning('请确认密码');
    return;
  }
  if (password.value!== passwordt.value) {
    ElMessage.warning('两次输入的密码不一致');
    return;
  }
  if (!isVerified.value) {
    ElMessage.warning('请先验证验证码');
    return;
  }
};

const sendVerifyCode = async () => {
  if (isSending.value || countdown.value > 0) return;
  
  if (!email.value) {
    ElMessage.warning('请输入邮箱');
    return;
  }
  
  if (!emailRegExp.test(email.value)) {
    ElMessage.warning('请输入正确的QQ邮箱格式');
    return;
  }
  
  isSending.value = true;
  
  try {
    await axios.post(`${API_BASE_URL}/send-login-code`, {
      email: email.value
    });
    
    ElMessage.success('验证码已发送，请查收邮箱');
    countdown.value = 60;
    startCountdown();
  } catch (error: any) {
    console.error('发送验证码失败:', error);
    ElMessage.error(error.response?.data?.message || '验证码发送失败，请重试');
  } finally {
    isSending.value = false;
  }
};

const verifyCodeFunc = async () => {
  if (isVerified.value) return;
  
  if (!email.value) {
    ElMessage.warning('请输入邮箱');
    return;
  }
  
  if (!verifyCode.value) {
    ElMessage.warning('请输入验证码');
    return;
  }
  
  if (verifyCode.value.length!== 6) {
    ElMessage.warning('验证码必须为6位');
    return;
  }
  
  try {
    const response = await axios.post(`${API_BASE_URL}/verify-code`, {
      email: email.value,
      code: verifyCode.value
    });
    
    if (response.data.code === 200) {
      isVerified.value = true;
      ElMessage.success('验证码验证成功');
    } else {
      ElMessage.error(response.data.message || '验证码错误或已过期');
    }
  } catch (error: any) {
    console.error('验证验证码失败:', error);
    ElMessage.error('验证码验证失败，请重试');
  }
};

const validateEmail = () => {
  if (!email.value) {
    ElMessage.warning('请输入邮箱');
    return;
  }
  
  if (!emailRegExp.test(email.value)) {
    ElMessage.warning('请使用@qq.com邮箱');
    return;
  }
};

const startCountdown = () => {
  if (countdownTimer) clearInterval(countdownTimer);
  
  countdownTimer = setInterval(() => {
    countdown.value--;
    
    if (countdown.value <= 0) {
      clearInterval(countdownTimer!);
      countdownTimer = null;
    }
  }, 1000);
};

onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
});
</script>

<style scoped>
.threelogin{
  display:flex;
  justify-content:center;
}
.threelogin img{
  width:10%;
  margin:0% 5%;
}
.button{
  width:70%;
  border-radius:50px;
  background-color:#54EA8C;
  border:0px;
  font-size:20px;
  margin-top: 20px;
  cursor: pointer;
  transition: all 0.3s;
}
.button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}
.check{
  padding:0% 16%;
  float:left;
  text-align:left;
  font-size:12px;
}
.title {
  font-style: italic; 
  text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
  letter-spacing: 0.5px; 
  font-size:55px;
  font-weight:800;
  text-align: center;
}
.login{
  padding-top:20vh;
}
.logins{
  padding-top:3vh;
  line-height:7vh;
}
.big {
  width:100%;
  height:100vh;
  background: linear-gradient(to bottom,hsl(182, 100.00%, 83.70%) 0%,white 100%);
  position: relative;
}
.bottom{
  margin-top:25vh;
}

.account-input{
  width: 70%;
  font-size: 16px;
  border:0px;
  height:5vh;
  background-color:#CAFDFF;
  padding: 0 10px;
  border-radius: 4px;
}
.account-inputo{
  width: 70%;
  font-size: 16px;
  border:0px;
  height:5vh;
  background-color:#D7FEFF;
  padding: 0 10px;
  border-radius: 4px;
}
.account-inputt{
  width: 70%;
  font-size: 16px;
  border:0px;
  height:5vh;
  background-color:#DDFEFF;
  padding: 0 10px;
  border-radius: 4px;
}
.verify-input {
  width: 50%;
  font-size: 16px;
  border:1px;
  height:7vh;
  background-color:#D3FEFF;
  padding: 0 10px;
  border-radius: 4px;
}

.verify-container {
  width:70%;
  border-bottom:0.1px solid #ccc;
  display:flex;
  justify-content:space-between;
}
.send-code-btn {
  width: 50%;
  color: #007BFF;
  border: none;
  font-size: 16px;
  background-color:#D3FEFF;
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 4px;
}
.send-code-btn:disabled {
  color: #999999;
  cursor: not-allowed;
}

.centered-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.centered-container {
  width:70%;
  border-bottom:0.1px solid #ccc;
  margin-bottom: 15px;
}

.back-button-container {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 100;
}
.back-button {
  padding: 5px 10px;
  background-color: #54EA8C;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}
.back-button:hover {
  background-color: #3ad075;
}
</style>